package com.solcoo.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;

/**
 * 发送短信
 */
public class SendMsgUtil implements Runnable {

	private static final String ac = "1001@500700010001";
	private static final String authkey = "F8D27993D72F8DB9009F0B21277DBE65";
	private static final String cgid = "51";
    private static Logger logger = Logger.getLogger(SendMsgUtil.class);
    
    private String mobile;
    private String content;
    private String stype;
    
    public SendMsgUtil(String mobile, String content) {
		super();
		logger.error("mobile="+mobile+";content="+content);
		this.mobile = mobile;
		this.content = content;
		this.stype = "1";
	}

    public SendMsgUtil(String mobile, String content, String stype) {
		super();
		logger.error("mobile="+mobile+";content="+content);
		this.mobile = mobile;
		this.content = content;
		this.stype = stype;
	}
    
    public void SendMsg() throws Exception{
    	String content2 = URLEncoder.encode(content, "UTF-8");
    	String sendT = "sendOnce";
    	if("1".equals(stype)) {
    		sendT = "sendBatch";
    	}
		String u = "http://smsapi.c123.cn/OpenPlatform/OpenApi?action=" + sendT + "&ac="
				+ ac +"&authkey=" + authkey + "&cgid=" + cgid + "&c=" + content2 + "&m=" + mobile;
		URL url = new URL(u);
		HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
		
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedDate = formatter.format(new Date());
		logger.error(formattedDate+":mobile=="+mobile+"；content=="+content);
		httpCon.connect();
		
		BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
		String result = in.readLine();
		logger.error("result=="+result);
    }
    
	@Override
	public void run() {
		try{
			SendMsg();
    	} catch(Exception e) {
    		logger.error("sendMsg error~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    		logger.error(e.getMessage(),e);
    	}
		
	}
}
